package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagerApi;
import com.xuecheng.api.content.model.file.UploadTokenResult;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author by it-song
 * @Date 2021/12/14
 * @Description
 */
@Slf4j
@RestController
public class FileManagerController implements FileManagerApi {

    @Autowired
    private RestTemplate restTemplate;

    /*
          nacos中的配置信息
    * #文件系统微服的请求地址
    file.service.url=http://127.0.0.1:56082/farming/generatetoken?origin=qiniu
    #文件存储空间名称
    file.service.bucket= heima136-song

    #文件存储区域的地址
    file.service.upload.region = http://upload.qiniu.com
    #文件访问的cdn加速域名
    cdn.domain = r414yd8z5.hd-bkt.clouddn.com

    file.token.type = 1
    file.token.deadline = 3600
    * */
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.token.type}")
    private String type;
    @Value("${file.token.deadline}")
    private int deadline;


    @GetMapping("common/qnUploadToken")
    public UploadTokenResult qiniuUploadToken() {
        // 1.发送请求获得文件上传出凭证
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("tokenType", type);
        hashMap.put("scope", bucket);
        hashMap.put("deadline", deadline);
        // 上传文件的key：唯一
        String key = UUID.randomUUID().toString() + RandomStringUtils.randomAlphanumeric(16);
        hashMap.put("key", key);
        ResponseEntity<Map> entity = restTemplate.postForEntity(url, hashMap, Map.class);

        int codeValue = entity.getStatusCodeValue(); //返回响应码
        if (HttpStatus.OK.value() == codeValue) {
        //如果返回的状态码不是200 有问题的话 就返回异常
            ExceptionCast.cast(ContentErrorCode.E_120020);
        }
        //如果返回的状态码是200没问题的话 返回凭证信息
        Map body = entity.getBody();
        // 2.将结果封装成前端所需要的内容并返回
        UploadTokenResult Token = new UploadTokenResult();
        Token.setTokenType(type);
        Token.setScope(bucket);
        Token.setKey(key);
        Token.setQnToken(body.get("result").toString()); //令牌
        Token.setUp_region(region);
        Token.setDomain(domain);
        Token.setDeadline(deadline);
        return Token;
    }
}
